package com.example.hello.utils;

import com.allqj.qjf.object_storage.AliyunBucketInfo;
import com.allqj.qjf.object_storage.AliyunOSSBucket;
import com.allqj.qjf.object_storage.AliyunOSSFunctionImpl;
import com.allqj.qjf.object_storage.spring.AliyunOSSInfoConfig;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Hashtable;

/**
 * @author sjw
 * @className PdfUtil
 * @date 2022/5/25 8:37
 * @description: TODO
 */
public class PdfUtil {

    public static void main(String[] args) {
        String key = "ceshi";
        String url = "https://qj-apk.oss-cn-beijing.aliyuncs.com/%E6%88%BF%E4%B8%BB-%E6%A0%87%E5%87%86%E7%89%882020.4.2%EF%BC%88ceshi%EF%BC%89.pdf";
        byte[] data;
        try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            PdfReader pdfReader = new PdfReader(new URL(url));
//            ByteArrayOutputStream output = new ByteArrayOutputStream();
            PdfStamper stamp = new PdfStamper(pdfReader, output);//new FileOutputStream("F:\\123.pdf"));


            System.out.println("------------------");
            AcroFields form = stamp.getAcroFields();
            form.getFields().forEach(((s, item) -> {
                System.out.println(s);
            }));
// 默认12号字体
            float fromFontSize = 12f;
            PdfString da = form.getFieldItem(key).getMerged(0).getAsString(PdfName.DA);
            if (da != null) {
                Object dab[] = AcroFields.splitDAelements(da.toUnicodeString());
                if (dab[AcroFields.DA_SIZE] != null)
                    fromFontSize = ((Float) dab[AcroFields.DA_SIZE]).floatValue();
            }

            // 设置中文字体
            BaseFont baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(baseFont);

            // 文本框宽度
            Rectangle position = form.getFieldPositions(key).get(0).position;
            float textBoxWidth = position.getWidth();
            // 文本框高度
            float textBoxHeight = position.getHeight();
            // 文本单行行高
            float ascent = baseFont.getFontDescriptor(baseFont.ASCENT, fromFontSize);
            // baseFont渲染后的文字宽度
            String value = "张金铜130999999999";
            float textWidth = baseFont.getWidthPoint(value, fromFontSize);

//            // 文本框高度只够写一行，并且文字宽度大于文本框宽度，则缩小字体
//            if (textBoxHeight < ascent * 1.6) {
//                while (textWidth > textBoxWidth) {
//                    fromFontSize--;
//                    textWidth = baseFont.getWidthPoint(value, fromFontSize);
//                }
//            }
//            form.setFieldProperty(key, "textsize", fromFontSize, null);
//            form.setFieldProperty(key, TextField.READ_ONLY, 1, null);
            form.setField(key, value);
            System.out.println("------------------");
            int pages = pdfReader.getNumberOfPages();
            // 透明度
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.3f);
            // 设置字体
            BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            int fontSize = 20;
            for (int page = 1; page <= pages; page++) {

                PdfContentByte content = stamp.getOverContent(page);

                Rectangle rectangle = pdfReader.getPageSizeWithRotation(page);
                content.setGState(gs);
                content.setFontAndSize(font, fontSize);
                content.setColorFill(BaseColor.PINK);
                float height = rectangle.getHeight();
                float width = rectangle.getWidth();
                System.out.println(height);
                System.out.println(width);
                if (page == 1) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(qr("合同验真(后续更换为页面跳转连接)"+value, 200, 200), "png", baos);
                    com.itextpdf.text.Image itextimage = Image.getInstance(baos.toByteArray());
                    itextimage.setAbsolutePosition(width - 150, height - 100);
                    // 边框固定
                    itextimage.scaleToFit(100, 100);
                    content.addImage(itextimage);
                    baos.close();
                }
                content.beginText();
                for (int h = fontSize; h < height; h = h + fontSize * 4) {
                    content.showTextAligned(Element.ALIGN_CENTER, "恒大御庭118楼1单元402", width / 4,
                            h, 45);
                    content.showTextAligned(Element.ALIGN_CENTER, "恒大御庭118楼1单元402", width * 3 / 4,
                            h, 45);
                }
//                content.showTextAligned(Element.ALIGN_MIDDLE, "测试", 180,
//                        340, 45);
                content.endText();
            }

            stamp.close();
            pdfReader.close();
            System.out.println(pdfReader.getNumberOfPages());
            data = output.toByteArray();
            System.out.println(data);


            AliyunOSSInfoConfig config = new AliyunOSSInfoConfig();
            config.setEndpoint("https://oss-cn-beijing.aliyuncs.com");
            config.setAccessKeyId("LTAIuBMF9MOPd8um");
            config.setSecretAccessKey("xfMahp9yACASmfcHrRGyLDvL3HX8T8");
            AliyunOSSBucket bucket = new AliyunOSSBucket();
            AliyunBucketInfo bucketInfo = new AliyunBucketInfo();
            bucketInfo.setBucketName("qjdev-pred-files");
            bucketInfo.setBucketUrl("https://qjdev-pred-files.oss-cn-beijing.aliyuncs.com/");
            bucket.setOther(bucketInfo);
            config.setBucket(bucket);
            AliyunOSSFunctionImpl aliyunOSSFunction = new AliyunOSSFunctionImpl(config, config.getBucket().getOther());


            String s = aliyunOSSFunction.add("contract", "123.pdf", new ByteArrayInputStream(data));
            System.out.println(s);

        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }

    public void waterMark(String url) {

        try (InputStream inputStream = new URL(url).openStream()) {

            PdfReader pdfReader = new PdfReader(new URL(url));

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static BufferedImage qr(String content, int qrWidth, int qrHeight) {
//        content="https://qjdev-pred-files.oss-cn-beijing.aliyuncs.com/contract/123.pdf";
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrWidth, qrHeight,
                    hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }
}
